package com.springboot.frame.socket.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ServerNettyChannelInitializer
 * @Author: liheng
 * @Date: 2018/9/25 15:43
 * @Description:
 */
@Component
public class ServerNettyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ServerNettyHandler serverNettyHandler;


    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //解决TCP粘包拆包的问题，以特定的字符结尾（$_）
        pipeline.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.copiedBuffer("$_".getBytes())));
        //字符串解码和编码
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        // 加入心跳机制
        pipeline.addLast(new IdleStateHandler(40, 0, 0, TimeUnit.SECONDS));
        // 服务器端的处理逻辑
        pipeline.addLast("fpsHandler", serverNettyHandler);
    }
}
